<?php
// TODO: dodawanie, edytowanie, usuwanie newsow
class Controller_Admin_News extends Controller_Admin_Abstract
{	
	public function __construct(Controller_Front $frontController)
	{
		parent::__construct('admin_news', $frontController);
	}
	
	public function indexAction()
	{
		$this->view()->display('admin_news.tpl');
	}
	
	public function newAction()
	{
		$news;
		$buttonName;
		
		if (isset($_GET['id_news'])) {
			$id = $_GET['id_news'];
			$buttonName = 'Edytuj';
			
			$news = NewsPeer::retrieveByPK($id);
		} else {
			$buttonName = 'Dodaj';
			$news = new News();
		}
		$this->view()->assign('news', $news);
		$this->view()->assign('vortals', VortalsPeer::doSelect(new Criteria()));
		$this->view()->assign('requeststatuses', RequeststatusesPeer::doSelect(new Criteria()));
		$this->view()->assign('editButton', $buttonName);
		$_SESSION['enable']=true;		
		$this->view()->display('admin_news_edit.tpl');
	}
	
	public function listAction()
	{
		$news = NewsPeer::doSelect(new Criteria());
		//var_dump($categories);
		$this->view()->assign('news', $news);
		
		$this->view()->display('admin_news_list.tpl');
	}
	
	public function checkAction()
	{		
		$news;
		
		if (!empty($_POST['id_news'])) {
			$id = $_POST['id_news'];
			
			$news = newsPeer::retrieveByPK($id);
		} else {
			$news = new News();
		}
		
		if($_SESSION["enable"]==true) {
		$news->setTitle($_POST['title']);
		$news->setUrlOriginal($_POST['url']);
		$news->setIntro($_POST['intro']);
		$news->setStory($_POST['story']);
		$news->setUrlImage($_POST['url_image']);
		$news->setIdUser(Manager_User::getUser()->getIdUser());
		$news->setIdVortal($_POST['id_vortal']);
		$news->setRequeststatuses(Manager_RequestStatus::getAwaiting());
		$news->setCategories(Manager_Category::getDefault());
		$news->save();
		$this->ok('News saved.');
		
		$tags = Manager_Tag::add(Manager_Tag::fromString($_POST['tags']));
		Manager_News::addTags($news, $tags);
		$news->setCategories(Manager_News::getBestCategory($news));
		$news->save();		
		$this->ok('News added.');
		
		$_SESSION['enable']=false;
		} else {
			$this->fail('Re-saving it is not possible.');
		}
		
	}	
	
	public function deleteAction()
	{
		
		if (!isset($_GET['id_news'])) {
			throw new Exception('id not spec');
		}	
		
		$id = $_GET['id_news'];
		try {
			NewsPeer::doDelete($id);
		} catch (Exception $e) {
			$this->view()->assign('fail_info', 'Nie udalo sie usunac ' 
				. $e->getMessage());  	
			return $this->view()->display('fail.tpl');		
		}
				
			
	}
	
}